package com.gezi.admin.module.config.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author 格子软件
 * @createDate 2024/2/10 09:00
 * @contact 公众号：格子软件 微信：13716343106 邮箱：1424529270@qq.com
 */
public class PageUtil {

    /**
     * Mybatis-Plus分页封装
     *
     * @param page
     * @return
     */
    public static Page initMpPage(PageVo page) {

        int current = page.getCurrent();
        int size = page.getSize();

        if (current < 1) {
            current = 1;
        }
        if (size < 1) {
            size = 10;
        }
        Page p = new Page(current, size);

        List<OrderItem> orderItemList = CollUtil.newArrayList();
        if(CollUtil.isNotEmpty(page.getOrders())){
            for (String order : page.getOrders()) {
                String column = StrUtil.toUnderlineCase(order.split(":")[0]);
                Boolean isAsc = Boolean.valueOf(order.split(":")[1]);
                orderItemList.add(isAsc?OrderItem.asc(column):OrderItem.desc(column));
            }
            p.setOrders(orderItemList);
        }
        return p;
    }

    /**
     * List 手动分页
     *
     * @param page
     * @param list
     * @return
     */
    public static List listToPage(PageVo page, List list) {

        int pageNumber = page.getCurrent() - 1;
        int pageSize = page.getSize();

        if (pageNumber < 0) {
            pageNumber = 0;
        }
        if (pageSize < 1) {
            pageSize = 10;
        }

        int fromIndex = pageNumber * pageSize;
        int toIndex = pageNumber * pageSize + pageSize;

        if (fromIndex > list.size()) {
            return new ArrayList();
        } else if (toIndex >= list.size()) {
            return list.subList(fromIndex, list.size());
        } else {
            return list.subList(fromIndex, toIndex);
        }
    }
}
